#coding:utf-8
from django.shortcuts import render
from menu.models import Menu
from django.forms import model_to_dict
# Create your views here.

Class MenuApi():

    def get (self,request):
        #获取所有父菜单
        parent_menu = Menu.objects.filter(parent=None)
        menu_dict = {}
        for menu in parent_menu:
            childs = Menu.objects.filter(parent=menu)
            menu_dict[menu.name] = [[child.name,child.url] for child in childs]
        
        return Response({'status':2000,'result':menu_dict,'message':'success'})
    
    def post (self,request):
        menu_type = request.data.get('menu_type')
        menu_name = request.data.get('menu_name')
        menu_url = request.data.get('menu_url')
        menu_parent = request.data.get('menu_parent')

        if menu_type == 'parent':
            Menu.objects.create(name=menu_name)
        else:
            parent_menu = Menu.objects.get(name=menu_parent)
            Menu.objects.create(name=menu_name,url=menu_url,parent=parent_menu)
        
        return Response({'status':2000,'result':{},'message':'success'})
    
    def get_all_parent_menu (self,request):
        parent_menu = Menu.objects.filter(parent=None)
        
        menus = [model_to_dict(parent_menu) for menu in parent_menu]
        return Response({'status':2000,'result':menus,'message':'success'})
        
        
    def get_menu_by_id (self,request):
        menu_id = request.data.get('menu_id')
        try:
            menu = Menu.objects.get(id=menu_id)
            menu = model_to_dict(menu)
        except:
            menu = {}
        return Response({'status':2000,'result':menu,'message':'success'})
        
    
    def delete_menu_by_id (self,request):
        menu_id = request.data.get('menu_id')
        try:
            menu = Menu.objects.get(id=menu_id)
            menu.delete()
        except:
            menu = {}
            msg = 'menu not found'
        
        return Response({'status':2000,'result':{},'message':msg})
    
    def delete_menu_by_ids (self,request):
        menu_ids = request.data.get('menu_ids')
        try:
            menus = Menu.objects.filter(id__in=menu_ids)
            menus.delete()
        except:
            msg = 'menu not found'
        
        return Response({'status':2000,'result':{},'message':msg})
    
    def update_menu (self,request):
        menu_id = request.data.get('menu_id')
        menu_name = request.data.get('menu_name')
        menu_url = request.data.get('menu_url')
        menu_parent = request.data.get('menu_parent')
        try:
            menu = Menu.objects.get(id=menu_id)
            menu_parent = Menu.objects.get(name=menu_parent)
            menu.name = menu_name
            menu.url = menu_url
            menu.parent = menu_parent
            menu.save()
            menu = model_to_dict(menu)
        except:
            menu = {}
        
        return Response({'status':2000,'result':menu,'message':'success'})
        
